<?php
namespace App\Cache;

/**
 * Class Cache
 * @package App\Cache
 */
class Cache
{
    /**
     * @var
     */
    protected $_di;
    /**
     * @var null
     */
    protected $_options;
    /**
     * @var
     */
    protected $_connect;

    /**
     * Cache constructor.
     *
     * @param null $options
     */
    public function __construct ($options = null)
    {
        $this->_options = $options;
    }

    /**
     * @param $di
     */
    public function setDI ($di)
    {
        $this->_di = $di;
    }

    /**
     * @return mixed
     */
    public function _connect ()
    {
        $options = $this->_options;
        if (isset($options['connect']))
        {
            $service = $options['connect'];
        }
        else
        {
            $service = 'redis';
        }
        return $this->_di->get($service);
    }

    /**
     * @param     $key
     * @param int $lifetime
     *
     * @return mixed
     */
    public function get ($key, $lifetime = 0)
    {
        $connect = $this->_connect;
        if (!is_object($connect))
        {
            $connect        = $this->_connect();
            $this->_connect = $connect;
        }
        return $connect->find($key, $lifetime);
    }

    /**
     * @param $key
     * @param $value
     * @param $lifetime
     *
     * @return mixed
     */
    public function save ($key, $value, $lifetime)
    {
        $connect = $this->_connect;
        if (!is_object($connect))
        {
            $connect        = $this->_connect();
            $this->_connect = $connect;
        }
        return $connect->save($key, $value, $lifetime);
    }

}